<template>
  <div class="page flex-center">
    <div class="sign-box">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="86px">
        <h3 class="title">{{ t('login') }}</h3>
        <!-- 账号 -->
        <el-form-item :label="t('form.username')" prop="account">
          <el-input v-model="form.account" :placeholder="t('form.usernameHolder')" prefix-icon="user"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item :label="t('form.password')" prop="password">
          <el-input v-model="form.password" type="password" :placeholder="t('form.passwordHolder')"
            prefix-icon="lock"></el-input>
        </el-form-item>

        <el-form-item label>
          <el-button type="primary" class="w100p" :loading="loading" @click="doLogin">{{ t('login') }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>


<script setup>

// 引入登录的方法
import { login } from '@/apis/login'
// import router from '../../router';

// 引入 router
const router = useRouter()
// 引入 Store
const store = useStore()
console.log(store);

// 引入i18n的转换方法
const { t } = useI18n()
// 获取表单实例
const formRef = ref()
// 登录表单属性
const form = reactive({
  account: 'admin',
  password: 'admin'
})



const rules = computed(() => {
  return {
    account: [
      {
        required: true,
        message: t('form.usernameHolder'),
        trigger: ['change', 'blur'] // 输入框内内容的改变以及失去焦点时触发
      },
      {
        pattern: /^[a-zA-Z][a-zA-Z0-9_-]{3,31}$/, // 字母开头，然后组成为 字母数字_- 的内容，长度为 3-31
        message: t('form.usernameError'),
        trigger: ['change', 'blur']
      }
    ],
    password: [
      {
        required: true,
        min: 4,
        message: t('form.passwordError'),
        trigger: ['change', 'blur'] // 输入框内内容的改变以及失去焦点时触发
      },
    ]
  }
})

// 登录时的按钮的loading效果
const loading = ref(false)

// 登录操作
const doLogin = () => {
  // 表单验证的方法
  formRef.value.validate((valid) => {
    console.log(valid);
    if (valid) {
      loading.value = true

      // console.log(login(form));
      login(form)
        .then(res => {
          // 设置登录的token
          store.commit('user/setToken', res.data.token)

          // 请求用户信息
          store.dispatch('user/refreshInfo')

          // 设置路由/菜单还没有加载
          store.commit('setRouteLoaded', false)

          // 去往首页
          router.push('/')
        }).finally(() => {
          loading.value = false
        })
    }
  })
}
</script>

<style lang="scss">
.page {
  height: 100%;
  // background: url(@/assets/bg.jpg) no-repeat;
  background-size: cover;
}

.sign-box {
  width: 400px;
  background: #fff;
  padding: 30px 50px 20px 30px;
  border-radius: 4px;
  box-shadow: 0 0 10px #022c44;
}

.title {
  text-align: center;
  font-size: 20px;
  line-height: 30px;
  margin-top: 0;
  margin-bottom: 10px;
  color: #000;
}
</style>